package com.zx.framework.plat.dept.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zx.framework.core.pagination.Pagination;
import com.zx.framework.core.util.BeanUtil;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.core.util.layer.IDUtil;
import com.zx.framework.plat.PlatController;
import com.zx.framework.plat.dept.po.Dept;
import com.zx.framework.plat.dept.service.DeptService;
import com.zx.framework.plat.dept.vo.DeptVo;
import com.zx.framework.plat.user.vo.UserVo;
import com.zx.framework.web.controller.BaseController;
import com.zx.framework.web.exception.AjaxException;
import com.zx.framework.web.exception.UIException;

@Controller
@RequestMapping("/dept")
public class DeptController extends PlatController {

    private static final Logger LOGGER = Logger.getLogger(DeptController.class);
    /**
     * 根节点
     */
    private static final String ROOT = "root";

    @InitBinder("dept")
    public void paramBinder(WebDataBinder binder) throws Exception {
        binder.setFieldDefaultPrefix("dept.");
    }

    /**
     * 分页查询方法
     *
     * @param dept       查询模板
     * @param pagination 分页
     * @return 分页模板路径
     */
    @RequestMapping("/page")
    public String query(Dept dept, Pagination<Dept> pagination, Model model) {
        try {
            model.addAttribute("dept", dept);
            model.addAttribute("pagination", deptService.pageQuery(dept, pagination.getPage(), pagination.getRows()));
        } catch (Exception e) {
            throw new UIException("获取部门列表信息失败！");
        }
        return "dept/list";
    }

    /**
     * 获取所有部门的json
     *
     * @return
     */
    @RequestMapping("/query/all")
    @ResponseBody
    public Object queryAll() {
        try {
            List<Dept> depts = deptService.findAll("layer");
            Map m = request.getParameterMap();
            return clientMap().success().message("获取成功！").datas(depts).getMap();
        } catch (Exception e) {
            LOGGER.error("", e);
            throw new AjaxException(e.getMessage());
        }
    }

    /**
     * 根据ID获取部门信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/query/id/{id}")
    @ResponseBody
    public Object queryDeptById(@PathVariable("id") String id) {
        try {
            Dept dept = deptService.findDeptById(id);
            if (dept == null) {
                throw new AjaxException("部门信息不存在！");
            }
            return clientMap().success().message("获取成功！").put("dept", dept).getMap();
        } catch (AjaxException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("", e);
            throw new AjaxException("获取部门信息失败！");
        }
    }

    @RequestMapping("/add")
    public String add() {
        try {
            //to-do
        } catch (Exception e) {
            throw new UIException("获取部门信息失败！");
        }
        return "dept/add";
    }
    /**
     * 添加部门
     * @param dept
     * @return
     */
    @RequestMapping("/add/save")
    @ResponseBody
    public Map<String, Object> addSave(Dept dept) {
    	if (dept == null) {
            throw new AjaxException(getMessage("e.save.po.null"));
        }
        try {
			validate(dept);
		} catch (Exception e) {
			LOGGER.error("",e);
			throw new AjaxException(e.getMessage());
		}
        try {
        	
        	List<Dept> temp = deptService.findByProperty("name", dept.getName());
        	if(!temp.isEmpty()){
        		throw new AjaxException(getMessage("e.object.not.null", "部门名称",dept.getName()));
        	}
        	if(StringUtil.isNotEmpty(dept.getOwner())){
        		Dept parent = deptService.findDeptById(dept.getOwner());
        		if(parent==null){
        			 throw new AjaxException(getMessage("e.object.parent.notexist"));
        		}else{
        			if(!deptService.canOperate(dept.getOwner(),getLoginUser().getDept().getId())){
        				throw new AjaxException(getMessage("e.not.permit"));
        			}
        		}
        		dept.setLabels(parent.getLabels()+"-"+dept.getName());
        	}else{
        		throw new AjaxException(getMessage("e.object.parent.notexist"));
        	}
        	String max = deptService.findMaxProperty(dept.getOwner(), "id", "layer");
        	dept.setId(IDUtil.increase(max, dept.getOwner()));
        	dept.setLayer(dept.getId());
        	dept.setOrders(dept.getId());
            deptService.saveDept(dept);
        	return clientMap().success().message(getMessage("op.ok")).put("dept", dept).getMap();
        } 
        catch (AjaxException e) {
        	LOGGER.error("",e);
            throw e;
        }
        catch (Exception e) {
        	LOGGER.error("",e);
            throw new AjaxException("获取部门信息失败！");
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(@RequestParam(value = "ids", required = false) List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new AjaxException("错误的请求参数！");
        }

        Map<String, Object> rs = new HashMap<String, Object>();
        rs.put("status", HttpStatus.OK.value());
        rs.put("message", "删除部门成功！");
        return rs;
    }
    /**
     * 获取当前部门的信息
     * @param id
     * @return
     */
    @RequestMapping("/load/json")
    @ResponseBody
    public Map<String, Object> loadJson(@RequestParam(value = "id") String id) {
        try {
			Dept dept = deptService.findDeptById(id);
			if (dept == null) {
			    throw new AjaxException(getMessage("e.object.notexist","部门"));
			}
			else{
				if(!deptService.canOperate(dept.getId(), getLoginUser().getDept().getId())){
    				throw new AjaxException(getMessage("e.not.permit"));
    			}
			}
			DeptVo vo = new DeptVo();
			BeanUtil.copyProperties(dept, vo);
			if(StringUtil.isNotEmpty(dept.getOwner())){
				Dept parent = deptService.findDeptById(dept.getOwner());
				if(parent != null){
					vo.setOwnerName(parent.getLabels());
				}
			}
			return clientMap().success().message("获取成功！").put("dept", vo).getMap();
		}
        catch (AjaxException e) {
        	LOGGER.error("",e);
            throw e;
        }
        catch (Exception e) {
        	LOGGER.error("",e);
            throw new AjaxException("获取部门信息失败！");
        }
    }
    /**
     * 修改部门
     * @param dept
     * @return
     */
    @RequestMapping("edit/save")
    @ResponseBody
    public Map<String, Object> editSave(Dept dept) {
    	try {
			validate(dept);
		} catch (Exception e) {
			throw new AjaxException(e.getMessage());
		}
		try {
			Dept saveDept = deptService.findDeptById(dept.getId());
			if (saveDept == null) {
				 throw new AjaxException(getMessage("e.object.notexist","部门"));
			}else{
				if(!deptService.canOperate(saveDept.getId(),getLoginUser().getDept().getId())){
    				throw new AjaxException(getMessage("e.not.permit"));
    			}
			}
			BeanUtil.extend(dept, saveDept);
			deptService.updateDept(saveDept);
			return clientMap().success().message(getMessage("op.ok")).put("dept", dept).getMap();
		} catch (AjaxException e) {
			LOGGER.error("",e);
            throw e;
        }
        catch (Exception e) {
        	LOGGER.error("",e);
            throw new AjaxException("获取部门信息失败！");
        }
    }
    
    /*附加的其他业务跳转*/
    /**
     * 获取子级的json
     * @param id
     * @return
     */
    @RequestMapping("query/child/json")
    @ResponseBody
    public Map<String,Object> queryChild(String id,String fuzzy){
    	
    	try {
    		//获取登录用户及其所在部门
    		UserVo login = getSessionObject(SESSION_KEY, UserVo.class); 
    		Dept userDept = login.getDept();
    		List<Dept> depts  = deptService.findChildren(id,userDept);
			return clientMap().success().message("获取成功！").datas(depts).getMap();
		} catch (Exception e) {
			LOGGER.error("",e);
			throw new AjaxException("获取子级部门失败："+e.getMessage());
		}
    }
    
    /**
     * 获取子级的json
     * @param id
     * @return
     */
    @RequestMapping("query/child/json/fuzzy")
    @ResponseBody
    public Map<String,Object> queryFuzzyChild(String fuzzy){
    	
    	try {
    		//获取登录用户及其所在部门
    		UserVo login = getSessionObject(SESSION_KEY, UserVo.class); 
    		Dept userDept = login.getDept();
    		List<Dept> depts  = deptService.findFuzzyChildren(userDept, fuzzy);
			return clientMap().success().message("获取成功！").datas(depts).getMap();
		} catch (Exception e) {
			LOGGER.error("",e);
			throw new AjaxException("获取子级部门失败："+e.getMessage());
		}
    }
}
